local skel = fk.CreateSkill {
  name = "rmt__sheizhuchenfu",
}

local function getMoveTypes(dat, player)
  local ret = {}
  for _, move in ipairs(dat) do
    if move.to == player and move.toArea == Card.PlayerHand then
      table.insertIfNeed(ret, "get")
    end
    if move.from == player and table.find(move.moveInfo, function(info)
      return info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip
    end) then
      table.insertIfNeed(ret, "lose")
    end
  end
  return ret
end

skel:addEffect(fk.TurnEnd, {
  anim_type = "drawcard",
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(skel.name) then return false end
    local current_event = player.room.logic:getCurrentEvent():findParent(GameEvent.Turn, true)
    if current_event == nil then return false end
    local last_event = player.room.logic:getEventsByRule(GameEvent.Turn, 1, function (e)
      return e.id < current_event.id
    end, 1)[1]
    if last_event == nil then return false end
    local room = player.room
    local current_type = {}
    room.logic:getEventsOfScope(GameEvent.MoveCards, 1, function(e)
      table.insertTableIfNeed(current_type, getMoveTypes(e.data, player))
      return #current_type == 2
    end, Player.HistoryTurn)
    if #current_type == 0 then return false end
    local last_type = {}
    room.logic:getEventsByRule(GameEvent.MoveCards, 1, function (e)
      if e.id > current_event.id then return false end
      table.insertTableIfNeed(last_type, getMoveTypes(e.data, player))
      return #last_type == 2
    end, last_event.id)
    current_type = table.filter(current_type, function(t) return table.contains(last_type, t) end)
    if #current_type > 0 then
      event:setCostData(self, current_type)
      return true
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local choice = room:askToChoice(player, {
      choices = table.map(event:getCostData(self), function(c) return "rmt__sheizhuchenfu_".. c end),
      skill_name = skel.name,
    })
    if choice:endsWith("_lose") then
      player:drawCards(2, self.name)
    else
      room:askToDiscard(player, {
        max_num = 2, min_num = 2, skill_name = skel.name, include_equip = true, cancelable = false
      })
    end
  end,
})

Fk:loadTranslationTable{
  ["rmt__sheizhuchenfu"] = "谁主沉浮",
  [":rmt__sheizhuchenfu"] = "每回合结束时，若你于上一个回合内与本回合内均：失去过牌，你摸两张牌；获得过牌，你弃置两张牌（若皆满足改为选一项执行）。",
  ["rmt__sheizhuchenfu_lose"] = "摸2张牌",
  ["rmt__sheizhuchenfu_get"] = "弃2张牌",
}

return skel
